<template>
  <div class="home-container">
    <!-- 搜索栏 -->
    <!-- <van-search
      v-model="searchValue"
      placeholder="充电宝"
      shape="round"
      background="#f7f8fa"
      @search="onSearch"
    /> -->
    <van-row align="center">
      <van-col span="2">
        <van-icon name="bars" size="30" style="margin-left: 4px" />
      </van-col>
      <van-col span="20">
        <van-search
          v-model="value"
          placeholder="请输入搜索关键词"
          shape="round"
          background="#f1f0ef"
        />
      </van-col>

      <van-col span="2">
        <van-icon name="user-circle-o" size="30" />
      </van-col>
    </van-row>
    <!-- 轮播图，显示isAd=1的商品 -->
    <van-swipe
      class="banner"
      :autoplay="3000"
      indicator-color="white"
      v-if="adProducts.length > 0"
    >
      <van-swipe-item
        v-for="(item, index) in adProducts"
        :key="index"
        @click="goToDetail(item.id)"
        st
      >
        <img :src="item.adImage" alt="广告图片" class="banner-img" />
        <div class="banner-title">
          <h3>{{ item.name }}</h3>
          <p>{{ item.description || "暂无描述" }}</p>
        </div>
      </van-swipe-item>
    </van-swipe>

    <!-- 分类图标 -->
    <div class="category-icons">
      <div
        class="category-item"
        v-for="(item, index) in categoryList"
        :key="index"
        @click="onCategoryClick(item)"
      >
        <van-image
          :src="item.categoryImage"
          width="50"
          height="50"
          fit="cover"
        />
        <p>{{ item.categoryName }}</p>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <van-grid
        :column-num="2"
        :gutter="10"
      
        v-if="normalProducts.length > 0"
      >
        <van-grid-item
          v-for="product in normalProducts"
          :key="product.id"
          @click="goToDetail(product.id)"
        >
          <div class="product-card">
            <van-image :src="product.displayImage" width="100%" fit="cover" />
            <div class="product-info">
              <h4 class="product-name">{{ product.name }}</h4>
              <p class="product-price">¥{{ product.salePrice }}</p>
              <p class="product-sold">已售{{ product.sold || 0 }}件</p>
            </div>
          </div>
        </van-grid-item>
      </van-grid>
      <!-- 无商品时显示空状态 -->
      <van-empty v-else description="暂无商品" />
    </div>

    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" color="#1989fa" />
    </div>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item icon="home-o" to="/ncwuShop/home">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o" to="/ncwuShop/category">分类</van-tabbar-item>
      <van-tabbar-item icon="cart-o" to="/ncwuShop/cart">购物车</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/ncwuShop/mine">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { listProduct } from "@/api/productManage/product";
import { useRouter } from "vue-router";
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
} from "@/api/categoryManage/category";
const { proxy } = getCurrentInstance();
const router = useRouter();
const searchValue = ref("");
const activeTabbar = ref(0);
const productList = ref([]);
const loading = ref(false);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: 1, // 只查询状态正常的商品
});

// 分类数据
const categoryList = ref([]);

/** 查询商品类目列表 */
function getList() {
  loading.value = true;
  listCategory().then((response) => {
    console.log("商品类目列表", response);
    if (response.code === 200) {
      // 根据后端接口返回的数据结构修改
      const categoriesData = response.data || [];

      // 处理图片路径
      categoryList.value = categoriesData.map((item) => {
        if (item.categoryImage && item.categoryImage.startsWith("/profile/upload")) {
          // 转换图片路径格式
          item.categoryImage =
            "http://www.zyf.com" + item.categoryImage.replace("/profile", "");
        }
        return item;
      });
      if (categoryList.value.length > 10) {
        categoryList.value = categoryList.value.slice(0, 10);
      }
      console.log("商品类目列表", categoryList.value);
    } else {
      console.error("获取商品类目列表失败：", response.msg);
    }
    loading.value = false;
  });
}

// 筛选广告商品（isAd=1）
const adProducts = computed(() => {
  return productList.value.filter(
    (item) => item.isAd === 1 && item.status === 1
  );
});

// 筛选非下架的普通商品（status=1）
const normalProducts = computed(() => {
  return productList.value.filter((item) => item.status === 1);
});

// 加载商品数据
const loadProducts = async () => {
  loading.value = true;
  try {
    const response = await listProduct(queryParams.value);
    if (response.code === 200) {
      // 根据后端接口返回的数据结构修改
      const productsData = response.rows || [];

      // 处理图片路径
      productList.value = productsData.map((item) => {
        item.salePrice = item.salePrice / 100;
        item.costPrice = item.costprice / 100;
        
        // 检查图片路径是否包含多个图片（逗号分隔）
        if (item.image) {
          const imageArray = item.image.split(',');
          
          // 为展示准备不同的图片
          item.displayImage = "";  // 商品列表展示用
          item.adImage = "";       // 广告轮播图展示用
          
          // 处理第一张图片 - 用于商品列表展示
          if (imageArray.length > 0 && imageArray[0]) {
            let firstImage = imageArray[0].trim();
            if (firstImage.startsWith("/profile/upload")) {
              item.displayImage = "http://www.zyf.com" + firstImage.replace("/profile", "");
            } else {
              item.displayImage = firstImage;
            }
          }
          
          // 处理广告图片 - 如果是广告商品且有第二张图片，则使用第二张作为广告图
          if (item.isAd === 1 && imageArray.length > 1 && imageArray[1]) {
            let secondImage = imageArray[1].trim();
            if (secondImage.startsWith("/profile/upload")) {
              item.adImage = "http://www.zyf.com" + secondImage.replace("/profile", "");
            } else {
              item.adImage = secondImage;
            }
          } else {
            // 如果没有第二张图片或不是广告商品，则广告图也使用第一张
            item.adImage = item.displayImage;
          }
        }
        
        return item;
      });

      console.log("商品列表", productList.value);
    } else {
      console.error("获取商品列表失败：", response.msg);
    }
  } catch (error) {
    console.error("获取商品列表失败", error);
  } finally {
    loading.value = false;
  }
};

// 搜索商品
const onSearch = () => {
  // 实现搜索功能
  queryParams.value.name = searchValue.value;
  queryParams.value.pageNum = 1;
  loadProducts();
};

// 点击分类
const onCategoryClick = (category) => {
  console.log("选择分类：", category.name);
  // 可以跳转到分类页面或者筛选当前商品列表
  queryParams.value.categoryId = category.id;
  queryParams.value.pageNum = 1;
  loadProducts();
};

// 跳转到商品详情
const goToDetail = (productId) => {
  router.push(`/ncwuShop/product/detail/${productId}`);
};

onMounted(() => {
  loadProducts();
  getList();
  // console.log(categoryList.value);
  // console.log(adProducts)
  // console.log(normalProducts)
});
</script>

<style scoped>
.home-container {
  padding-bottom: 40px;
  background-color:rgb(245, 245, 245);
}

.banner {
  height: 200;
  position: relative;
}

.banner-img {
  width: 100%;
  height: 200;
  object-fit: cover;
}

.banner-title {
  position: absolute;
  bottom: 20px;
  left: 20px;
  color: #ffffff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.banner-title h3 {
  margin: 0;
  font-size: 24px;
}

.banner-title p {
  margin: 5px 0 0;
  font-size: 14px;
}

.category-icons {
  display: flex;
  flex-wrap: wrap;
  padding: 15px 0;
  background-color: #fff;
}

.category-item {
  width: 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.category-item p {
  margin-top: 5px;
  font-size: 12px;
  color: #323233;
}

.promotion-banner {
  margin: 10px 0;
  position: relative;
}

.promotion-content {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  font-weight: bold;
  color: #ff6034;
}

.product-list {
  padding: 0px;
}

.product-card {
  width: 100%;
  height: 250px;
  overflow: hidden;
  border-radius: 8px;
  background-color:rgb(255, 255, 255);
}

.product-info {
  padding: 3px;
}

.product-name {
  margin: 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  /* -webkit-line-clamp: 2; */
  -webkit-box-orient: vertical;
}

.product-price {
  margin: 5px 0;
  font-size: 16px;
  font-weight: bold;
  color: #f44;
}

.product-sold {
  margin: 0;
  font-size: 12px;
  color: #969799;
}

.empty-banner {
  height: 200px;
  position: relative;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
